package com.tencent.org.service.impl;


import com.tencent.basic.util.PageList;
import com.tencent.org.domain.Department;
import com.tencent.org.domain.Emp;
import com.tencent.org.mapper.DepartmentMapper;
import com.tencent.org.query.DepartmentQuery;
import com.tencent.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void del(Long id) {
        departmentMapper.del(id);
    }

    @Override
    @Transactional
    public void add(Department department) {
        departmentMapper.add(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        departmentMapper.update(department);
    }

    @Override
    public List<Department> findAll() {
        return departmentMapper.findAll();
    }

    @Override
    public PageList<Department> queryPage(DepartmentQuery departmentQuery) {
        // 查询数据的总条数
        Integer totals = departmentMapper.queryCount(departmentQuery);
        if (totals == 0){
            return new PageList<>();
        }
        // 查询当前页的数据
        List<Department> data = departmentMapper.queryData(departmentQuery);
        return new PageList<>(data, totals);

    }

    @Override
    public void patchDel(List<Long> ids) {
        departmentMapper.patchDel(ids);
    }

    @Override
    public List<Department> departmentTree() {
        List<Department> departments = departmentMapper.findAll();
        // 把所有部门装在MAP中
        Map<Long, Department> map = new HashMap<>();
        for (Department department: departments) {
            // 将部门名字和部门信息装进map中
            map.put(department.getId(), department);
        }
        // 查询部门树
        List<Department> departmentTree = new ArrayList<>();
        for (Department department: departments) {
            if (department.getParent_id() == null){
                // 如果没有父部门id，则为顶级部门，则把他加到部门树的集合中
                departmentTree.add(department);
            }else{
                // 如果又父部门id，获取到父部门的id
                Long parent_id = department.getParent_id();
                // 通过父部门的id获取到父部门
                Department parentDepartment = map.get(parent_id);
                // 再把自己装进父部门的子集合Children中
                parentDepartment.getChildren().add(department);
            }
        }
        return departmentTree;
    }

    @Override
    public Department findById(Long id) {
        return departmentMapper.findById(id);
    }
}
